using Triad.Web;

namespace Triad.Framework
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Triad.Model;

    /// <summary>
    /// The framework page.  All javascript is loaded within the DOM associated with this page.
    /// Required for the framework to work. 
    /// </summary>
    /// <remarks>
    /// Author: tim.fischer,   7/9/2008 - 10:17 AM
    /// Modified By: 
    /// </remarks>
    public partial class MainMenuPage : Triad.Web.UI.Page
    {
        private bool isLogon;

        protected void Page_Load(object sender, EventArgs e)
        {
            isLogon = Request.RawUrl.StartsWith("/mainmenu.aspx?t=logon", StringComparison.CurrentCultureIgnoreCase);
            if (!isLogon && !User.Identity.IsAuthenticated)
            {
                Response.Redirect("/MainMenu.aspx?T=Logon");
            }

            StringBuilder strScript = new StringBuilder();
            ClientScriptManager cm = Page.ClientScript;
            strScript.AppendLine("<script type=\'text/javascript\'>");
            strScript.AppendLine("_TF.PageTitle = _gE(\'" + lnkBtnTitle.ClientID + "\');");

            // Create JS WebResourceLinks for Images
            string sTmp = "~/fw/controls";
            if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["Triad.Controls"]))
            {
                sTmp = ConfigurationManager.AppSettings["Triad.Controls"];
            }
            strScript.Append("_TF.ControlDir='" + sTmp + "';");

            sTmp = "~/_fw/theme/red";
            WebProfile pc = WebProfile.GetProfile(User.Identity.Name);
            if (User.Identity.IsAuthenticated) // Does user have own preference for color?
            {
                if (!String.IsNullOrEmpty(pc.Theme))
                {
                    sTmp = "~/_fw/theme/" + pc.Theme;
                    
                }
            }
            else if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["Theme"]))
            {
                sTmp = ConfigurationManager.AppSettings["Theme"];
            }


            strScript.Append("_TF.Theme='" + sTmp + "';");
            strScript.AppendLine("</script>");
            if (!cm.IsStartupScriptRegistered("gMainScript"))
            {
                cm.RegisterStartupScript(GetType(), "gMainScript", strScript.ToString());
                AddCSS("cssMain", sTmp + "/appmain.css");
                AddCSS("cssCommon", sTmp + "/appcommon.css");
                AddCSS("cssLog", sTmp + "/tfNLog.css");
                AddCSS("cssPopup", sTmp + "/tfpopup.css");
                AddCSS("cssAccord", sTmp + "/accordian.css");
                AddCSS("cssClueTip", sTmp + "/jquery.cluetip.css");
            }

            if (isLogon || userObj == null || !User.Identity.IsAuthenticated)
            {
                ifMainContent.Attributes["src"] = "/Login.aspx";
            }
            else
            {
                userObj.Theme = sTmp;
                userObj.MachineID = Page.Request.ServerVariables["REMOTE_ADDR"];
                RenderMenu();
                ifMainContent.Attributes["src"] = "/views/Welcome.aspx";
            }
        }

        /// <summary>
        /// Encrypts the specified string to encrypt.
        /// </summary>
        /// <param name="stringToEncrypt">The string to encrypt.</param>
        /// <param name="SEncryptionKey">The S encryption key.</param>
        /// <returns></returns>
        public string Encrypt(string stringToEncrypt, string SEncryptionKey)
        {
            byte[] IV = new byte[] {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};

            try
            {
                byte[] key = Encoding.UTF8.GetBytes(SEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        protected void btnLogOff_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            HttpCookie authCookie = HttpContext.Current.Response.Cookies.Get(FormsAuthentication.FormsCookieName);
            if (authCookie != null) authCookie.Expires = DateTime.Now;
            Session.Abandon();
            Session["AppLogon"] = null;
            Response.Write("<script language=\'javascript\'> { window.close();}</script>");
        }

        /// <summary>
        /// Render the menu from the Database
        /// </summary>
        private void RenderMenu()
        {
            var menuItems = new Triad.BLL.framework().getMenuItems("en-US", true);
            var query = (menuItems.Where(c => c.MenuItemIdParent == 0)).AsEnumerable();

            foreach (var item in query)
            {
                if (CheckAccess(item.MenuItemLabel))
                {
                    wb.Controls.Add(menuCreateHeader(item.MenuItemLabel));
                    menuCreateBody(null, null, menuItems, item.MenuItemId.Value, false);
                }
            }
        }

        /// <summary>
        /// Create the Header item for the generated jQuery Accordian Menu
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        private static Panel menuCreateHeader(string text)
        {
            HyperLink a = new HyperLink {Text = text};
            Panel div = new Panel {CssClass = "mhead"};
            div.Controls.Add(a);

            return div;
        }

        /// <summary>
        /// Create the body of the Menu Item using a treeview control
        /// </summary>
        /// <param name="tv">TreeView control</param>
        /// <param name="tn">Tree Node</param>
        /// <param name="menuItems">Enumerated list of menu items</param>
        /// <param name="itemId">current menu item ID</param>
        /// <param name="isChildNode">Is this a childnode?</param>
        private void menuCreateBody(TreeView tv, TreeNode tn, IEnumerable<usp_MenuItems_SelectResult> menuItems,
                                    int itemId, bool isChildNode)
        {
            WebControl p = null;
            Panel div = null;

            if (tv == null) // First Time through
            {
                p = new WebControl(HtmlTextWriterTag.P);
                div = new Panel {CssClass = "mbody"};
                tv = new TreeView {NoExpandImageUrl = "", ImageSet = TreeViewImageSet.Arrows};
                tv.ParentNodeStyle.Font.Bold = false;
                tv.HoverNodeStyle.Font.Bold = false;
                tv.NodeStyle.Font.Name = "Verdana";
                tv.NodeStyle.Font.Size = FontUnit.Point(10);
                tv.NodeStyle.ForeColor = System.Drawing.Color.Black;
                tv.NodeStyle.HorizontalPadding = Unit.Pixel(5);
                tv.NodeStyle.NodeSpacing = Unit.Pixel(0);
                tv.NodeStyle.VerticalPadding = Unit.Pixel(0);
                tv.SelectedNodeStyle.Font.Underline = true;
                tv.SelectedNodeStyle.ForeColor = System.Drawing.Color.Crimson;
                tv.SelectedNodeStyle.HorizontalPadding = Unit.Pixel(0);
                tv.SelectedNodeStyle.VerticalPadding = Unit.Pixel(0);
            }

            var query = (menuItems.Where(c => c.MenuItemIdParent == itemId)).ToArray();

            foreach (var item in query)
            {
                // Target = "ifMainContent", 
                tn = new TreeNode
                         {
                             Text = item.MenuItemLabel,
                             NavigateUrl = "javascript:TF.APP.Common.contentRedirect('" + item.TargetUrl + "');"
                         };

                tv.Nodes.Add(tn);

                usp_MenuItems_SelectResult item1 = item;
                var query2 = (menuItems.Where(d => d.MenuItemIdParent == item1.MenuItemId.Value)).ToArray();
                foreach (var item2 in query2)
                {
                    if (CheckAccess(item2.MenuItemLabel))
                    {
                        menuCreateBody(tv, tn, query2, item2.MenuItemId.Value, true);
                        TreeNode tn2 = new TreeNode
                                           {
                                               Text = item2.MenuItemLabel,
                                               NavigateUrl =
                                                   "javascript:TF.APP.Common.contentRedirect('" + item2.TargetUrl +
                                                   "');"
                                           };
                        tn.ChildNodes.Add(tn2);
                    }
                }
            }

            if (p != null)
            {
                p.Controls.Add(tv);
                div.Controls.Add(p);
                wb.Controls.Add(div);
            }
        }
    } //leftNavigation
}